import easyocr
import os.path as ospath
from util import ImageUtil
from PIL import ImageGrab
import config.config
import numpy


class OCR:
    _instance = None
    _temp_pic_path = ospath.join(config.config.SCRIPT_OCR_PIC_PATH, 'screenshot.png')

    @staticmethod
    def instance():
        if OCR._instance is None:
            OCR._instance = easyocr.Reader(['ch_sim', 'en'])

        return OCR._instance

    # 返回结果, [
    #     [
    #       text, confidence,
    #       [
    #           [left-bottom-x, y], [bottom-right-x, y], [right-topx, y], [left-topx, y]
    #       ]
    #     ],
    #     [
    #       text, confidence,
    #       [
    #           [left-bottom-x, y], [bottom-right-x, y], [right-topx, y], [left-topx, y]
    #       ]
    #     ], ...
    # ]
    @staticmethod
    def ocr(img):
        return OCR.instance().readtext(img)

    @staticmethod
    def ocrInScreen(region=None):
        # ImageUtil.grab(OCR._temp_pic_path, region)
        recoImg = ImageGrab.grab(bbox=region)
        return OCR.ocr(numpy.array(recoImg))

    @staticmethod
    def textPos(img, text):
        result = OCR.ocr(img)
        for idx in range(len(result)):
            res = result[idx]
            recText = res[1]
            if text in recText:
                return res[0]

        return None

    @staticmethod
    def screenTextPos(text, region=None):
        result = OCR.ocrInScreen(region=region)
        print(result)
        for idx in range(len(result)):
            res = result[idx]
            recText = res[1]
            if text in recText:
                return res[0]

        return None
